# author: axin
# date: 2021/4/21 20:32
# description:

from rest_framework import serializers
from fdfs_client.client import Fdfs_client
from django.conf import settings
from rest_framework.response import Response

from goods.models import SKUImage, SKU


class ImagesSerialziers(serializers.ModelSerializer):
    """
        商品图片序列化器
    """

    # sku = serializers.StringRelatedField()
    sku_id = serializers.IntegerField()  # 返回sku_id

    class Meta:
        model = SKUImage
        fields = "__all__"

    def create(self, validated_data):
        # 建立fastdfs的客户端
        client = Fdfs_client(settings.FASTDFS_PATH)

        # 序列化器里有一个self.context['request'] 序列化器中获取request对象
        file = self.context['request'].FILES.get('image')
        # 上传图片
        res = client.upload_by_buffer(file.read())
        # 判断是够上传成功
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError({'error': '图片上传失败'})
        # 保存图片表
        img = SKUImage.objects.create(sku=validated_data['sku'], image=res['Remote file_id'])

        return img

    def update(self, instance, validated_data):
        # 建立fastdfs的客户端
        client = Fdfs_client(settings.FASTDFS_PATH)

        # 序列化器里有一个self.context['request'] 序列化器中获取request对象
        file = self.context['request'].FILES.get('image')
        # 上传图片
        res = client.upload_by_buffer(file.read())
        # 判断是够上传成功
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError({'error': '图片上传失败'})
        # 更新图片表
        instance.image = res['Remote file_id']
        instance.save

        return instance


class SKUSerializer(serializers.ModelSerializer):
    """
        SKU序列化器
    """

    class Meta:
        model = SKU
        fields = ('id', "name")
